package edu.mtu.citizenscience.streamapplication.activity.main;

import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;

import edu.mtu.citizenscience.streamapplication.activity.DBHelper;
import edu.mtu.citizenscience.streamapplication.activity.R;
import edu.mtu.citizenscience.streamapplication.activity.R.layout;
import edu.mtu.citizenscience.streamapplication.activity.R.menu;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

public class SCPhotoNotesActivity extends Activity {

	// DataBase Stuff
	private DBHelper myDbHelper;
	private Long rowID;
	public static final String ROW_ID = "ROW_ID";
    private Cursor report;
    
    // Activity Elements
    private EditText notesText;
    
    // Camera
	private static final String TAG = "PhotoIntentActivity";
	private static final int ACTION_TAKE_PHOTO_B = 1;
	private static final String JPEG_FILE_PREFIX = "IMG_";
	private static final String JPEG_FILE_SUFFIX = ".jpg";
	
	private String Photo1 = null;
	private String Photo2 = null;
	private String Photo3 = null;

    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		// Included (needed)
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_scphoto_notes);
		
		// DataBase Initialization
		myDbHelper = new DBHelper(this);
		myDbHelper.open();
		
		// Assign Elements
		notesText = (EditText) findViewById(R.id.siteNotes);
		
		// Camera Stuff
		Log.d(TAG, "onCreate: savedInstanceState: "+savedInstanceState);
		
		// Photo 1
		ImageButton picBtn1 = (ImageButton) findViewById(R.id.btnPhoto1);
		setBtnListenerOrDisable( 
				picBtn1, 
				mTakePicOnClickListener,
				MediaStore.ACTION_IMAGE_CAPTURE
		);
	    
		// Photo 2
		ImageButton picBtn2 = (ImageButton) findViewById(R.id.btnPhoto2);
		setBtnListenerOrDisable( 
				picBtn2, 
				mTakePicOnClickListener,
				MediaStore.ACTION_IMAGE_CAPTURE
		);
		
		// Photo 3
		ImageButton picBtn3 = (ImageButton) findViewById(R.id.btnPhoto3);
		setBtnListenerOrDisable( 
				picBtn3, 
				mTakePicOnClickListener,
				MediaStore.ACTION_IMAGE_CAPTURE
		);
		
	    // DataBase Setup
	    rowID = this.getIntent().getLongExtra(this.ROW_ID, -1);
	    populateFields();
	}

	// If data exists already
	private void populateFields() {
		
		report = myDbHelper.fetchReport(rowID, "Photo_Notes");
		
		if (report.getCount() == 1) {
			
			notesText.setText(report.getString(report.getColumnIndexOrThrow("notes")));
		}
		
		
	}
	
	// Camera
	// ------------------------------------------------------------------------------------------------------------------------------
	ImageButton.OnClickListener mTakePicOnClickListener = 
			new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				dispatchTakePictureIntent(ACTION_TAKE_PHOTO_B);
			}
		};

		private void dispatchTakePictureIntent(int actionCode) {
			Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				File f = null;
				try {
					f = createImageFile();
					Log.d(TAG,"dispatchTakePictureIntent: f="+f);
					takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
				} catch (IOException e) {
					e.printStackTrace();
					f = null;
				}
				
			startActivityForResult(takePictureIntent, actionCode);
		} // end dispatchTakePictureIntent()

		/*
		 * Return from the Camera Activity
		 */
		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			Log.d(TAG,"onActivityResult: data="+data);
			if (requestCode == ACTION_TAKE_PHOTO_B) {
				if (resultCode == RESULT_OK) {
					Log.d(TAG,"onActivityResult: ACTION_TAKE_PHOTO_B");
					handleBigCameraPhoto();
				}
			} // ACTION_TAKE_PHOTO_B
		} // end onActivityResult()
		
		private void handleBigCameraPhoto() {
			Log.d(TAG,"handleBigCameraPhoto");
			/*
			 * RLP: should check for file size and
			 * if small, should delete.
			 */
		} // end handleBigCameraPhoto()
		
		
		// RLP: some methods for setting up the file
		private File createImageFile() throws IOException {
			// Create an image file name
			String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date(0, 0, 0));
			String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
			File albumF = getAlbumDir();
			File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
			return imageF;
		}
		
		private File getAlbumDir() {
			File storageDir = null;
			if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
				storageDir = new File(Environment.getExternalStoragePublicDirectory(
					Environment.DIRECTORY_PICTURES), getString(R.string.album_name));
				if (storageDir != null) {
					if (! storageDir.mkdirs()) {
						if (! storageDir.exists()){
							Log.d(TAG, "failed to create directory CameraSample");
							return null;
						}
					}
				}	
			} else {
				Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
			}
			return storageDir;
		} // end getAlbumDir()


		// RLP: some methods for checking the hardware 
		// and setting up the button
		private void setBtnListenerOrDisable( 
				ImageButton btn, 
				ImageButton.OnClickListener onClickListener,
				String intentName
		) {
			if (isIntentAvailable(this, intentName)) {
				btn.setOnClickListener(onClickListener);        	
			} else {
				//btn.setText( 
				//	getText(R.string.cannot).toString() + " " + btn.getText());
				btn.setClickable(false);
			}
		} // end setBtnListenerOrDisable()
		
		/**
		 * Indicates whether the specified action can be used as an intent. This
		 * method queries the package manager for installed packages that can
		 * respond to an intent with the specified action. If no suitable package is
		 * found, this method returns false.
		 * http://android-developers.blogspot.com/2009/01/can-i-use-this-intent.html
		 *
		 * @param context The application's environment.
		 * @param action The Intent action to check for availability.
		 *
		 * @return True if an Intent with the specified action can be sent and
		 *         responded to, false otherwise.
		 */
		public static boolean isIntentAvailable(Context context, String action) {
			final PackageManager packageManager = context.getPackageManager();
			final Intent intent = new Intent(action);
			List<ResolveInfo> list =
				packageManager.queryIntentActivities(intent,
						PackageManager.MATCH_DEFAULT_ONLY);
			return list.size() > 0;
		}
		
		//-----------------------------------------------------------------------------------------
		
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.scphoto_notes, menu);
		return true;
	}
	

	
	// When Save is pressed
	public void cont(View view) {
		saveData();
		myDbHelper.close();
		
		this.finish();
	}
	
	// Save the data
	private void saveData() {
		// TODO Auto-generated method stub
		
		// If new data
		if(report.getCount() == 0){
			
			myDbHelper.createPhotoNotes(rowID, 
					Photo1, //Photo 1
					Photo2, //Photo 2
					Photo3, //Photo 3
					notesText.getText().toString());
		}
		
		else{ //Editing
			
			myDbHelper.updatePhotoNotes(rowID,
					Photo1, //Photo 1
					Photo2, //Photo 2
					Photo3, //Photo 3
					notesText.getText().toString());
		}
		
	}

	// Back Button Pressed
	@Override
    public void onBackPressed() {
        super.onBackPressed();   
        myDbHelper.close();
        this.finish();
    }
	
	// Cancel Button Pressed
	public void cancel(View view){
		this.finish();
	}

}
